package com.cip.common.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ApiServiceUtil {
	
	
	private static Log logger = LogFactory.getLog(com.cip.common.util.ApiServiceUtil.class);
	
	/**
	 * <p>
	 * Make api call using given URL to get response as string and return.
	 * </p>
	 * @param strURL
	 * @return String
	 */
	public static String apiServiceCallGet(String strURL) {
		
		HttpClient httpclient = new HttpClient();
		
		GetMethod method = new GetMethod(strURL);
		
		byte[] responseBody = null;
		
		try{
			
			int statusCode = httpclient.executeMethod(method);
			
			logger.info("status in api service get call : "+statusCode);
			
			if (statusCode != HttpStatus.SC_OK) {
		        System.err.println("Method failed: " + method.getStatusLine());
			}
			
			responseBody = method.getResponseBody();
			
		}catch(Exception e){
			logger.error("==========error===" + e.getMessage() +"\n====e==="+e.getStackTrace());
		} finally {
			method.releaseConnection();
        }
		
		return new String(responseBody);
	}
	
	/**
	 * <p>
	 * Api post service call to radaptive 
	 * </p>
	 * @param strURL
	 * @return
	 * @throws Exception
	 */
	public static String apiServiceCallPost(String strURL){
		
		HttpClient httpclient = new HttpClient();
		
		logger.info("Url in post call to fetch the value :"+strURL);
		
		PostMethod post = new PostMethod(strURL);
		
		byte[] responseBody = null;
		
		try{
			
			int statusCode = httpclient.executeMethod(post);
			
			logger.info("status in api service post call : "+statusCode);
			
			if (statusCode != HttpStatus.SC_OK) {
		        System.err.println("Method failed: " + post.getStatusLine());
			}
			responseBody = post.getResponseBody();
			
		}catch(Exception e){
			logger.error("==========error===" + e.getMessage() +"\n====e==="+e.getStackTrace());
		} finally {
			post.releaseConnection();
        }
		
		return new String(responseBody);
	}
	
	

}
